package top.oneit.jdownload.controller;

import javafx.fxml.Initializable;
import javafx.stage.Stage;
import org.hibernate.Session;
import top.oneit.jdownload.JdownloadApplication;
import top.oneit.jdownload.stages.HomeStage;

import javax.persistence.EntityManager;
import java.net.URL;
import java.util.ResourceBundle;

/**
 * @author lingkang
 * @date 2021/11/19
 */
public class BaseInitializable implements Initializable {
    @Override
    public void initialize(URL location, ResourceBundle resources) {

    }

    protected Session getSession() {
        return JdownloadApplication.sessionFactory.getCurrentSession();
    }

    protected EntityManager getEntityManager() {
        return JdownloadApplication.sessionFactory.createEntityManager();
    }

    protected <T> T save(T o) {
        Session session = JdownloadApplication.sessionFactory.getCurrentSession();
        session.beginTransaction();
        session.save(o);
        session.getTransaction().commit();
        return o;
    }

    protected Stage getHomeStage() {
        return JdownloadApplication.stages.get(HomeStage.class.getName());
    }

    /**
     * 获取对象,,注意返回空值
     */
    protected <T> T getStage(Class<T> clazz) {
        Stage stage = JdownloadApplication.stages.get(clazz.getName());
        if (stage == null)
            return null;
        return (T) JdownloadApplication.stages.get(clazz.getName());
    }
}
